package com.example.library_common.base;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.example.library_common.R;
import com.example.library_common.utils.KeyboardUtils;
import com.example.library_common.view.web_view.JssAdvancedWebView;

import org.greenrobot.eventbus.EventBus;

public class BaseH5Fragment extends BaseFragmentEx implements JssAdvancedWebView.Listener {

    @Override
    public Object getLayoutId() {
        return R.layout.base_h5_fragment;
    }

    protected JssAdvancedWebView mJssAdvancedWebView;

    protected ProgressBar progressBar1, onReload;

    protected boolean isReady = false;

    protected LinearLayout header_layout;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        onReload = view.findViewById(R.id.onReload);
        mJssAdvancedWebView = view.findViewById(R.id.mJssAdvancedWebView);
        mJssAdvancedWebView.setListener(this, this);
        progressBar1 = view.findViewById(R.id.progressBar1);
        header_layout = view.findViewById(R.id.header_layout);


        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            WebSettings settings = mJssAdvancedWebView.getSettings();
            settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
            settings.setDomStorageEnabled(true);
            settings.setJavaScriptEnabled(true);
            settings.setBlockNetworkImage(false);
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            settings.setLoadsImagesAutomatically(true);
            settings.setAllowFileAccess(true);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                settings.setAllowUniversalAccessFromFileURLs(true);
                settings.setAllowFileAccessFromFileURLs(true);
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            }

        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            WebView.setWebContentsDebuggingEnabled(true);
        }

        mJssAdvancedWebView.addJavascriptInterface(BaseH5Fragment.this, "$android");

        mJssAdvancedWebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress == 100) {
                    progressBar1.setVisibility(View.GONE);

                } else {
                    progressBar1.setVisibility(View.VISIBLE);
                    progressBar1.setProgress(newProgress);
                }

            }
        });

        mJssAdvancedWebView.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                boolean should=shouldOverrideUrlLoadingPage(view, url);
                if (should){
                    return true;
                }
                view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                isReady = false;
                progressBar1.setVisibility(View.VISIBLE);
                progressBar1.setProgress(0);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                isReady = true;
                onWebPageFinished(view, url);
            }
        });
    }

    protected boolean shouldOverrideUrlLoadingPage(WebView view, String url) {
        return false;
    }


    protected void onWebPageFinished(WebView view, String url) {

    }


    @JavascriptInterface
    public void onCloseSoftKeyboard() {
        hideSoftInput();
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        if (mJssAdvancedWebView != null) {
            mJssAdvancedWebView.onResume();
        }
//        KeyboardUtils.registerSoftInputChangedListener(_mActivity, this);
    }


    @Override
    public void onResume() {
        super.onResume();
        if (mJssAdvancedWebView != null) {
            mJssAdvancedWebView.onResume();
        }
//        KeyboardUtils.registerSoftInputChangedListener(_mActivity, this);
    }

    @Override
    public boolean onBackPressedSupport() {
        if (mJssAdvancedWebView.canGoBack()) {
            mJssAdvancedWebView.goBack();
            return true;
        }
        return super.onBackPressedSupport();
    }

    @Override
    public void onPause() {
        super.onPause();
        mJssAdvancedWebView.onPause();
//        onSoftInputChanged(0);
        hideSoftInput();
        KeyboardUtils.unregisterSoftInputChangedListener(_mActivity);
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void onDestroy() {
        super.onDestroy();
        WebView.setWebContentsDebuggingEnabled(false);
        mJssAdvancedWebView.setWebChromeClient(null);
        mJssAdvancedWebView.setWebViewClient(null);
        mJssAdvancedWebView.onDestroy();
//        KeyboardUtils.unregisterSoftInputChangedListener(_mActivity);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mJssAdvancedWebView.onActivityResult(requestCode, resultCode, data);

    }

    @Override
    public void onPageStarted(String url, Bitmap favicon) {

    }

    @Override
    public void onPageFinished(String url) {

    }

    @Override
    public void onPageError(int errorCode, String description, String failingUrl) {

    }

    @Override
    public void onDownloadRequested(String url, String suggestedFilename, String mimeType, long contentLength, String contentDisposition, String userAgent) {

    }

    @Override
    public void onExternalPageRequest(String url) {

    }

//    @Override
//    public void onSoftInputChanged(int height) {//键盘弹出高度
//        double heightRadio = height * 1.0 / mJssAdvancedWebView.getHeight();
//        exec("javascript:onSoftHeight(" + heightRadio + ")");
//    }


//    protected void exec(final String trigger) {
//        if (isReady) {
//            load(trigger);
//        } else {
//            mJssAdvancedWebView.postDelayed(() -> exec(trigger), 100);
//        }
//    }

    private void load(String trigger) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mJssAdvancedWebView.evaluateJavascript(trigger, null);
        } else {
            mJssAdvancedWebView.loadUrl(trigger);
        }
    }


}
